package com.cu.jiekong.mqhandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cu.jiekong.frame.CacheManager;
import com.cu.jiekong.service.BorrowInfoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 借款审核mq消息处理
 *
 * @author jintian
 * @date 17:12
 */
@Component
@RabbitListener(queues = "borrowAuditor")
public class BorrowAuditorMqHandler {

    private Logger logger = LoggerFactory.getLogger(BorrowAuditorMqHandler.class);

    private static String ANDITOR_SUCCESS_CODE = "success";

    @Autowired
    private BorrowInfoService borrowInfoService;

    @Autowired
    private CacheManager cacheManager;

    private static String BORROW_AUDITOR_HEADER_KEY = "borrow_auditor_";

    private static long BORROW_AUDITOR_LOCK_TIME = 36000;

    @RabbitHandler
    public void handlerMsg(String msg) {
        if (StringUtils.isBlank(msg)) {
            return;
        }
        boolean auditorStatus = false;
        try {
            // 解析消息
            JSONObject jsonObject = JSON.parseObject(msg);
            logger.info("BorrowAuditorMqHandler.handlerMsg params: " + jsonObject.toJSONString());
            String code = jsonObject.getString("code");
            int borrowId = jsonObject.getInteger("borrowId");
            String auditorMsg = jsonObject.getString("msg");
            // 加分布式锁
            if (cacheManager.lock(BORROW_AUDITOR_HEADER_KEY + borrowId, BORROW_AUDITOR_LOCK_TIME)) {
                // TODO 有没有必要，如果这样还需要加锁么？
                // 看是否处理过了
                if(!borrowInfoService.hasAuditor(borrowId)){
                    // 判断审核是否通过
                    if (ANDITOR_SUCCESS_CODE.equals(code)) {
                        auditorStatus = true;
                    }
                    // 更新借款信息
                    borrowInfoService.updateAuditorInfo(borrowId, auditorStatus, auditorMsg);
                }
                // 解除锁
                cacheManager.unlock(BORROW_AUDITOR_HEADER_KEY + borrowId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("解析借款审核信息入库失败");
        }
    }
}
